<template>
  <div>
    <el-card>
      <el-steps :active="activeName-0" finish-status="success">
        <el-step title="基本信息"/>
        <el-step title="商品静态参数"/>
        <el-step title="商品动态参数"/>
        <el-step title="商品图片"/>
        <el-step title="商品内容"/>
        <el-step title="完成"/>
      </el-steps>

      <el-form ref="addFormRule" :model="addForm" :rules="addFormRules" label-width="100px" class="addForm">
        <el-tabs v-model="activeName" :tab-position="tabPosition" :before-leave="beforeLeave">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="addForm.name"/>
            </el-form-item>
            <el-form-item label="商品价格" prop="price">
              <el-input v-model="addForm.price"/>
            </el-form-item>
            <el-form-item label="商品数量" prop="number">
              <el-input v-model="addForm.number" type="number"/>
            </el-form-item>
            <el-form-item label="商品权重" prop="weight">
              <el-input v-model="addForm.weight"/>
            </el-form-item>
            <el-form-item label="商品分类">
              <el-cascader v-model="selectedKeys" clearable :options="optionsList" separator=" > "
                           :props="{ expandTrigger: 'hover', label: 'name', value: 'id' }" @change="changeSelected"/>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品静态参数" name="1">
            <el-form-item v-for="s in attrStatusList" :key="s.id" :label="s.name">
              <el-input v-model="s.val"/>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品动态参数" name="2">
            <el-form-item v-for="d in attrDynamicList" :key="d.id" :label="d.name">
              <el-checkbox-group v-model="d.val">
                <el-checkbox v-for="(dc,index) in d.val" :key="index" :label="dc"/>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              action="http://127.0.0.1:5000/goods/goods_image"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :file-list="fileList"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.introduce"/>
            <el-button type="primary" class="addGoodButton" @click="addGoodButton">新增</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <el-dialog title="图片显示" :visible.sync="imgVisible" width="30%">
      <img :src="imgUrl" alt="">
      <span slot="footer" class="dialog-footer">
        <el-button @click="imgVisible = false">取 消</el-button>
        <el-button type="primary" @click="imgVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import {cate, getCateAttrs} from '@/api/category'
import {getAttrs} from '@/api/attr'
import {addGoods} from '@/api/goods'

export default {
  name: 'AddGood',
  data() {
    return {
      tabPosition: 'left',
      activeName: '0',
      addForm: {
        name: '',
        price: '',
        number: '',
        weight: '',
        state: 0,
        is_promote: 0,
        hot_number: 15,
        cid_one_id: '',
        cid_two_id: '',
        cid_three_id: '',
        pics: [], // 上传文件的列表
        introduce: '',
        static_attrs: [],
        dynamic_attrs: []
      },
      addFormRules: {
        name: [
          {required: true, message: '请输入商品名称', trigger: 'blur'}
        ],
        price: [
          {required: true, message: '请输入商品价格', trigger: 'blur'}
        ],
        number: [
          {required: true, message: '请输入商品数量', trigger: 'blur'}
        ],
        weight: [
          {required: true, message: '请输入商品权重', trigger: 'blur'}
        ]
      },
      optionsList: [],
      selectedKeys: [],
      attrStatusList: [], // 静态参数列表
      attrDynamicList: [], // 动态参数列表
      fileList: [],
      imgVisible: false,
      imgUrl: ''
    }
  },
  created() {
    this.getCategoryList()
  },
  methods: {
    // 获取商品分类
    async getCategoryList() {
      const res = await cate()
      if (res.code !== 200) return this.$message.error('获取分类数据失败！')
      this.optionsList = res.data
    },
    // 级联选择框的变化
    changeSelected() {
      if (this.selectedKeys.length < 3) return
      this.addForm.cid_one_id = this.selectedKeys[0]
      this.addForm.cid_two_id = this.selectedKeys[1]
      this.addForm.cid_three_id = this.selectedKeys[2]
    },
    // tabs离开前的方法
    beforeLeave(activeName, oldActiveName) {
      if (this.selectedKeys.length < 3) {
        this.$message.warning('请选择商品分类！！！')
        return false
      }
      if (activeName === '1') return this.getAttrs('static')
      if (activeName === '2') return this.getAttrs('dynamic')
    },
    // 获取商品参数的方法
    async getAttrs(_type) {
      const res = await getCateAttrs(this.selectedKeys[this.selectedKeys.length - 1], _type)
      if (res.code !== 200) return this.$message.error('获取静态参数失败！')
      if (_type === 'static') {
        this.attrStatusList = res.data.attrs
      } else {
        res.data.attrs.forEach(item => {
          item.val = item.val ? item.val.split(',') : []
        })
        this.attrDynamicList = res.data.attrs
      }
    },
    // 点击已经上传文件的回调
    async handlePreview(file) {
      this.imgVisible = true
      const filename = await file.response.data.path.split('/').pop()
      try {
        const result = await this.imageCode(filename)
        const blob = new Blob([result.data], {type: result.data.type})
        const imageUrl = URL.createObjectURL(blob) // 创建 URL 对象
        this.imgUrl = imageUrl // 将url配置给img标签
      } catch (error) {
        console.error('显示图片预览失败:', error)
      }
    },
    // 获取图片的接口
    async imageCode(filename) {
      try {
        const response = await axios.get(`/goods/uploads/${filename}`, {responseType: 'blob'})
        return response // 返回 Blob 对象
      } catch (error) {
        console.error('获取图片失败:', error)
        throw error
      }
    },
    // 删除已经上传文件的回调
    handleRemove(file) {
      const i = this.addForm.pics.findIndex(x => x === file.response.data.path)
      this.addForm.pics.splice(i, 1)
    },
    // 上传成功后的回调
    handleSuccess(file) {
      this.addForm.pics.push(file.data.path)
    },
    // 新增商品的按钮
    addGoodButton() {
      // 数据处理
      const staticList = []
      this.attrStatusList.forEach(item => {
        staticList.push(item.id)
      })
      const dynamicList = []
      this.attrDynamicList.forEach(item => {
        dynamicList.push(item.id)
      })
      this.addForm.static_attrs = staticList
      this.addForm.dynamic_attrs = dynamicList
      this.addForm.pics = JSON.stringify(this.addForm.pics)
      console.log(JSON.stringify(this.addForm))
      // 提交按钮
      this.$refs.addFormRule.validate(async (valid) => {
        if (valid) {
          const res = await addGoods(JSON.stringify(this.addForm))
          if (res.code !== 200) return this.$message.error('新增商品失败！')
          this.$message.success('新增商品成功！')
          this.$router.push('/product_list')
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
.el-tabs {
  margin-top: 20px;
}

.el-cascader {
  width: 300px;
}

img {
  width: 100%;
}

::v-deep .ql-container {
  height: 400px;
}

.addGoodButton {
  margin-top: 20px;
}
</style>
